package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1. 保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        //2.补全套餐菜品关系
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        //3.保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishList);
    }

    /**
     * 删除套餐，同时需要删除套餐和菜品的关联数据
     */
    @Override
    @Transactional
    public void removewithDish(List<Long> ids) {
        //1. 查询套餐状态，确定是否可用删除
        QueryWrapper<Setmeal> queryWrapper1 =new QueryWrapper<>();
        queryWrapper1.in(ids.size()>0,"id",ids);
        queryWrapper1.eq("status",1);
        int count = this.count(queryWrapper1);
        if (count>0){
            throw new CustomerException("该套餐正在售卖,不能删除");
        }

        //2.可以删除
        //先删除套餐表中的数据
        this.removeByIds(ids);
        //再删除 setmeal_dish 表中数据
        QueryWrapper<SetmealDish> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.in("setmeal_id",ids);
        setmealDishService.remove(queryWrapper2);
    }
}
